package com.example.weight.wormHandle.cultivate;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.weight.R;
import com.example.weight.arrayAdapter.MyAdapter;
import com.example.weight.config.Config;
import com.example.weight.greenSeasons.flocculation.xuningguzhang;
import com.example.weight.greenSeasons.waterDeal.RepairTable;
import com.example.weight.util.WeightActivity;
import com.example.weight.wormHandle.garbageDisposal.researchDevelopment.BatchGroupNumber;
import com.example.weight.wormHandle.garbageDisposal.researchDevelopment.OutcomingSceneInsectSeparate;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BigBugBreedOut extends AppCompatActivity {
    private TitleBar titleBar;
    private String name, selectBatchText, factory;
    private  int belongTo_id = -1;


    private Spinner batchGroupNumber;
    private EditText end_time;
    private EditText after_big_weight;
    private EditText go_where;

//    private Button activeButton;

    //备选批次等列表
//    private List<String> batchList;
    private List<BatchGroupNumber> batchGroupNumberList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_big_bug_breed_out);

        Intent previousIntent = getIntent();
        name = previousIntent.getStringExtra("name");
        factory = previousIntent.getStringExtra("factory");
//        System.out.println(factory);

        titleBar=findViewById(R.id.titleBar);
        titleBar.setOnTitleBarListener(new OnTitleBarListener() {

            @Override
            public void onLeftClick(View v) { BigBugBreedOut.this.finish();}

            @Override
            public void onTitleClick(View v) { }
            @Override
            public void onRightClick(View v) { }
        });

        batchGroupNumber = findViewById(R.id.select_batch);
        end_time=findViewById(R.id.big_bug_breed_end_time);
        after_big_weight=findViewById(R.id.after_big_weight);
        go_where=findViewById(R.id.go_where);


//        batchList = new ArrayList<>();
        batchGroupNumberList = new ArrayList<>();

//        //获取当天最新一条数据
//        RequestQueue queue = Volley.newRequestQueue(this);
//        String url = Config.url + "/hsmpy/middleWormBreedingMaterial/getlatest";
//        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
//                new Response.Listener<String>() {
//                    @Override
//                    public void onResponse(String response) {
//                        try {
//                            JSONObject jsonObject = new JSONObject(response);
//                            JSONObject data;
//                            if(jsonObject.get("data")!=null && !jsonObject.get("data").toString().equals("null")){
//                                data = jsonObject.getJSONObject("data");
//                                Log.d("LB", data.toString());
//                                if (!data.isNull("id")) {
//                                    end_time.setText(data.getString("endTime"));
//                                    after_big_weight.setText(data.getString("after_big_weight"));
//                                    go_where.setText(data.getString("go_where"));
//                                    Toast.makeText(BigBugBreedOut.this,
//                                            "今日已填写此表", Toast.LENGTH_SHORT).show();
//                                }
//                            }else {
//                                end_time.setHint("2020-01-01");
//                            }
//                        } catch (JSONException e) {
//                            e.printStackTrace();
//                        }
//                    }
//                }, new Response.ErrorListener() {
//            @Override
//            public void onErrorResponse(VolleyError error) {
//                Toast.makeText(BigBugBreedOut.this,
//                        "获取信息失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
//            }
//        });
//        stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
//                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
//        queue.add(stringRequest);


        //获取3-3待填写的批次、组别、中虫盒号列表
        RequestQueue queue = Volley.newRequestQueue(this);
        String url2 = Config.url + "/hsmpy/middleWormBreedingMaterial/getlist" + "?factory=" + factory;
        StringRequest stringRequest2 = new StringRequest(Request.Method.GET, url2,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            if (!jsonObject.isNull("data")) {
                                JSONArray data = jsonObject.getJSONArray("data");
                                if( data.length()>0 ){
                                    for (int i=0; i < data.length(); i++){
                                        JSONObject record = data.getJSONObject(i);
                                            batchGroupNumberList.add(new BatchGroupNumber(record.getInt("id"), record.getString("batch"), record.getString("wormGroup"), record.getString("bigBugBreedBoxNumber"), "", record.optString("bigBugBreedEndTime")));
                                    }
                                    Log.d("batchGroupNumberList", batchGroupNumberList.toString());
                                    ArrayAdapter<BatchGroupNumber> adapter = new ArrayAdapter<BatchGroupNumber>(BigBugBreedOut.this, android.R.layout.simple_spinner_item,batchGroupNumberList);
                                    batchGroupNumber.setAdapter(adapter);
                                    batchGroupNumber.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                                        @Override
                                        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                                            belongTo_id = batchGroupNumberList.get(position).id;
                                            end_time.setText(batchGroupNumberList.get(position).date);//设置时间修改
                                        }

                                        @Override
                                        public void onNothingSelected(AdapterView<?> parent) {
                                            belongTo_id = -1;
                                        }
                                    });
                                    batchGroupNumber.setSelection(0,true);
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(BigBugBreedOut.this,
                        "获取信息失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
        stringRequest2.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(stringRequest2);
    }

    @SuppressLint("ResourceType")
    public void chooseEndDate(View view) {
        Calendar calendar=Calendar.getInstance();
        new DatePickerDialog(BigBugBreedOut.this,2,
                new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year,
                                          int month, int day) {
                        // TODO Auto-generated method stub
                        Integer mYear = year;
                        Integer mMonth = month;
                        Integer mDay = day;
                        end_time.setText(new StringBuilder()
                                .append(mYear)
                                .append("-")
                                .append((mMonth + 1) < 10 ? "0"
                                        + (mMonth + 1) : (mMonth + 1))
                                .append("-")
                                .append((mDay < 10) ? "0" + mDay : mDay));
                    }
                }
                // 设置初始日期
                , calendar.get(Calendar.YEAR)
                , calendar.get(Calendar.MONTH)
                , calendar.get(Calendar.DAY_OF_MONTH)).show();
    }


    public void save(View view) {
        if (belongTo_id == -1) {
            Toast.makeText(this, "请选择批次、组别、中虫盒号", Toast.LENGTH_SHORT).show();
            return;
        }
        if(end_time.getText().toString().equals("")) {
            Toast.makeText(this, "请填写中虫培育结束日期", Toast.LENGTH_SHORT).show();
            return;
        }
        if (after_big_weight.getText().toString().equals("")) {
            Toast.makeText(this, "请填写中虫培育后盒+料总重量", Toast.LENGTH_SHORT).show();
            return;
        }
        if (go_where.getText().toString().equals("")) {
            Toast.makeText(this, "请填写去向", Toast.LENGTH_SHORT).show();
            return;
        }

        new AlertDialog.Builder(this)
                .setTitle("确定保存吗？")
                .setCancelable(false)
                .setNegativeButton("取消", ((dialog, which) ->
                        Toast.makeText(this, "取消保存", Toast.LENGTH_SHORT).show()))
                .setPositiveButton("确定", (dialog, which) -> {

                    //提交请求
                    RequestQueue queue = Volley.newRequestQueue(this);
                    String url = Config.url + "/hsmpy/middleWormBreedingMaterial/add";
                    StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {
                                    //Toast.makeText(RepairTable.this, "保存成功", Toast.LENGTH_SHORT).show();
                                    Log.d("LB", response);
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        String code = jsonObject.getString("code");
                                        if (code.startsWith("2"))
                                            Toast.makeText(BigBugBreedOut.this,
                                                    "保存成功", Toast.LENGTH_SHORT).show();
                                        else
                                            Toast.makeText(BigBugBreedOut.this,
                                                    "保存失败", Toast.LENGTH_SHORT).show();
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Toast.makeText(BigBugBreedOut.this, "保存失败", Toast.LENGTH_SHORT).show();
                            Log.d("jy", error.toString());
                        }
                    }) {
                        @Override
                        protected Map<String, String> getParams() throws AuthFailureError {
                            Map<String, String> map=new HashMap<>();
                            map.put("id", belongTo_id+"");
                            map.put("big_bug_breed_end_time", end_time.getText().toString());
                            map.put("after_big_weight", after_big_weight.getText().toString());
                            map.put("go_where", go_where.getText().toString());
                            map.put("factory",factory);
                            return map;
                        }
                    };
                    stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                            DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                    queue.add(stringRequest);
                })
                .show();
    }
}